.pc = * "HUD routines"

.import source "hud_macros.asm"

.label hud_mem_start = $bc00
.label hud_mem_end = $c000

hud_draw_string:
{
.label string_color = zero_page_start
.label text_ptr = zero_page_start+1 // two bytes
.label dest_ptr = zero_page_start+3 // two bytes
.label color_ptr = zero_page_start+5 // two bytes    

    stx text_ptr
    sty text_ptr+1
    tax
    lda #0
    sta color_ptr
    lda #$d8
    sta color_ptr+1
    lda #<hud_mem_start
    sta dest_ptr
    lda #>hud_mem_start
    sta dest_ptr+1

    // compute offset from line number
    cpx #0
loop1:
    beq loop1done
    :AddLit8To16(color_ptr, 40)
    :AddLit8To16(dest_ptr, 40)    
    dex
    jmp loop1
loop1done:

    ldy #0
    ldx string_color
loop:
    lda (text_ptr),y
    cmp #255
    beq done
    sta (dest_ptr),y
    txa
    sta (color_ptr),y
    iny
    bne loop

    // y wrapped
    inc text_ptr+1
    inc dest_ptr+1
    inc color_ptr+1

    jmp loop

done:
    rts
}

hud_init:
{
    // fill beginning of hud memory with 0's
    lda #0
start:
    ldx #0
loop:
store_instr:
    sta hud_mem_start,x // this address gets modified
    inx
    bne loop
    ldx store_instr+2
    inx
    stx store_instr+2
    // switch to 32's after a page
    lda #32
    cpx #>hud_mem_end
    bne start

    // restore the instruction to its initial state
    ldx #>hud_mem_start
    stx store_instr+2

    // set all sprites to point to beginning of our memory
    lda #<[hud_mem_start/64]
    .for (var i = 8; i > 0; i--)
    {
        sta [hud_mem_end-i]
    }
}
    
hud_enable:
{
    // text mode
    lda $d011
    and #%10011111
    tay
    
    // select bank 2 ($8000-$bfff) for graphics
    lda $dd00
    and #252
    ora #1

    // set character RAM location, video RAM location
    ldx #$f6

    sta $dd00
    sty $d011
    stx $d018

    // not multicolor
    lda $d016
    and #%11101111
    sta $d016

    rts
}
